package alfred.mdp.worker;

import alfred.mdp.Majordomo;
import alfred.mdp.utils.Shutdowner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 */
public class HeartbeatTask implements Runnable {
    private static final Logger LOG = LoggerFactory.getLogger(HeartbeatTask.class);
    private static final String DEFAULT_LOG_MESSAGE = "HeartbeatTask of worker {} and service {} - ";
    private final Worker worker;

    public HeartbeatTask(Worker worker) {
        this.worker = worker;
    }

    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                Thread.sleep(Majordomo.HB_INTERVAL);
                if (LOG.isDebugEnabled()) {
                    LOG.debug(DEFAULT_LOG_MESSAGE + "sending heartbeat", worker.getId(), worker.getService().getName());
                }
                worker.sendHb();

            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();

            } catch (RuntimeException e) {
                LOG.error("Error", e);

            }
        }
        Shutdowner.shutdownCompleted(worker.getShutdownGroup(), getClass());
        LOG.debug(DEFAULT_LOG_MESSAGE + "shutdown completed", worker.getId(), worker.getService().getName());
    }
}
